package com.note.simpleshop.module.order.controller;
import com.note.simpleshop.constant.PayTypeConstant;
import com.note.simpleshop.module.cart.service.CartService;
import com.note.simpleshop.module.cart.vo.CartVo;
import com.note.simpleshop.constant.ErrorCode;
import com.note.simpleshop.entity.TbAddress;
import com.note.simpleshop.exception.NotDataException;
import com.note.simpleshop.module.order.dto.OrderDto;
import com.note.simpleshop.module.order.exception.OrderStatusException;
import com.note.simpleshop.module.order.exception.StockException;
import com.note.simpleshop.module.order.service.OrderService;
import com.note.simpleshop.module.order.vo.OrderVo;
import com.note.simpleshop.module.user.auth.RequestToken;
import com.note.simpleshop.module.user.auth.UserUtils;
import com.note.simpleshop.module.user.service.AddressService;
import com.note.simpleshop.utils.GsonUtil;
import com.note.simpleshop.utils.WebUtil;
import com.note.simpleshop.vo.Msg;
import com.note.simpleshop.vo.PageBean;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order/order")
public class OrderController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    @Autowired
    private CartService cartService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private OrderService orderService;
    /***
     *
     *
     * 返回用户的收货地址，用户的可选优惠劵，运费
     *
     * @param cartIds
     * @return
     */
    @ApiOperation(value = "settlement", notes = "用户在购物车中心结算")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header")})
    @PostMapping(value = "settlement")
    @RequestToken
    public Msg settlement(String cartIds) {
        logger.info("***************cartIds={}",cartIds);
        Msg msg = new Msg();
        try {
            List<String> listIds=GsonUtil.fromJsonList(cartIds,String.class);
            if(listIds.size()<1) {
                msg.setErrorCode(ErrorCode.ERROR_1000000);
                msg.setMsg("cartIds不为空且必须大于0");
            }
            else {
                List<CartVo> cartVoList=cartService.findByCardIds(UserUtils.currentUserId(),listIds);
                Map<String,Object> map=new HashMap<String, Object>();
                map.put("cart",cartVoList);
                msg.setErrorCode(ErrorCode.ERROR_0000);
                msg.setData(map);
            }
        }
        catch (Exception e) {
            logger.error(e.getMessage());
            msg.setErrorCode(ErrorCode.ERROR_1000001);
            msg.setMsg("系统异常");
        }
        return msg;
    }
    @ApiOperation(value = "createOrder", notes = "创建订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header")})
    @PostMapping(value = "createOrder")
    @RequestToken
    public Msg createOrder(OrderDto orderDto) {
        Msg msg = new Msg();
        try {
            if (StringUtils.isBlank(orderDto.getAddressId())) {
                msg.setErrorCode(ErrorCode.ERROR_1000000);
                msg.setMsg("addressId无效");
            }
            if (orderDto.getCartIds().size()==0) {
                msg.setErrorCode(ErrorCode.ERROR_1000000);
                msg.setMsg("cartIds无效");
            }
            if (PayTypeConstant.set.contains(orderDto.getPayType())) {
                msg.setErrorCode(ErrorCode.ERROR_1000000);
                msg.setMsg("payType无效");
            }
            String currentUserId = UserUtils.currentUserId();
            Map map=orderService.createOrder(currentUserId, orderDto.getAddressId(), orderDto.getCartIds(), orderDto.getCouponIds(),orderDto.getPayType(), WebUtil.getRemoteIp());
            msg.setErrorCode(ErrorCode.ERROR_0000);
            msg.setData(map);
            msg.setMsg("ok");
        } catch (NotDataException e) {
            logger.error(e.getMessage());
            msg.setErrorCode(ErrorCode.ERROR_1000000);
            msg.setMsg(e.getMessage());
        } catch (StockException e) {
            logger.error(e.getMessage());
            msg.setErrorCode(ErrorCode.ERROR_1000000);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            msg.setErrorCode(ErrorCode.ERROR_1000002);
            msg.setMsg(e.getMessage());
        }
        return msg;
    }
    @PostMapping("notifyUrl")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request){
        String res=getPostRequestBody(request);
        return orderService.callbackConfirmOrder(res);
    }
    public String getPostRequestBody(HttpServletRequest req) {
        if (req.getMethod().equals("POST")) {
            StringBuilder sb = new StringBuilder();
            try (BufferedReader br = req.getReader()) {
                char[] charBuffer = new char[128];
                int bytesRead;
                while ((bytesRead = br.read(charBuffer)) != -1) {
                    sb.append(charBuffer, 0, bytesRead);
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
            return sb.toString();
        }
        return "";
    }
    @ApiOperation(value = "orderList", notes = "我的订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header"),
            @ApiImplicitParam(name="orderStatus",value="all所有,0待付款，1待发货,已付款，2已发货，3交易成功",dataType="string", paramType = "query",example="xingguo")})

    @PostMapping("orderList")
    @ResponseBody
    @RequestToken
    public Msg orderList(String orderStatus,Integer pageNumber)
    {
        Msg msg = new Msg();
        String currentUserId=UserUtils.currentUserId();
        try {
            PageBean<OrderVo> pageBean=orderService.findByPage(currentUserId,orderStatus,pageNumber);
            msg.setErrorCode(ErrorCode.ERROR_0000);
            msg.setData(pageBean);
        } catch (OrderStatusException e) {
            logger.info(e.getMessage());
            msg.setErrorCode(ErrorCode.ERROR_1000002);
            msg.setMsg("订单状态错误");
        }
        return msg;
    }
}
